package cn.tedu.micro.demo.rabbitmq.amqp;

import cn.tedu.micro.demo.rabbitmq.pojo.UserMsg;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class DemoConsumer {
    /**
     * 消费类bean对象 会在底层通道被消费方法 delivery.handle调用
     * channel.basicConsume("demo-queue",true,delivery)
     * public void handle(String consumerTag,Delivery message){
     *  String msg=new String(message.getBody())
     *  demoConsumer.consume01(msg)
     * }
     */
    /*@RabbitListener(queues="demo-queue")
    public void consume01(String msg){
        log.info("消费者01接收到消息:{}",msg);
    }*/
    /**
     * 消费类bean对象 会在底层通道被消费方法 delivery.handle调用
     * channel.basicConsume("demo-queue",true,delivery)
     * public void handle(String consumerTag,Delivery message){
     *  Messge message=message.toMessage(message)
     *  demoConsumer.consume02(message)
     * }
     */
    /*@RabbitListener(queues="demo-queue")
    public void consume02(Message message){
        //1.自己反序列化
        //2.多接收 发送传递的属性
        //message.getMessageProperties().getPriority();//优先级
        byte[] body = message.getBody();
        //message.getMessageProperties().getMessageId();
        String msg=new String(body);
        log.info("消费者02接收到消息:{}",msg);
    }*/

    /**
     * 消费类bean对象 会在底层通道被消费方法 delivery.handle调用
     * channel.basicConsume("demo-queue",true,delivery)
     * public void handle(String consumerTag,Delivery message){
     *  demoConsumer.consume03(channel)
     * }
     */
    /*@RabbitListener(queues="demo-queue")
    public void consume03(Channel channel){
        //消费完毕之后 手动确认 消费成功 消费失败
        //channel.basicReject();
        log.info("消费者03接收到channel:{}",channel);
    }*/
    /*@RabbitListener(queues="demo-queue")
    public void consume04(String msg,Message message,Channel channel){
        log.info("消费者04接收到消息体:{}",msg);
        byte[] body = message.getBody();
        String msg1=new String(body);
        log.info("消费者04接收到消息对象解析body:{}",msg1);
        //按照消费逻辑 实现消息确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //如果手动确认失败,底层会按照basiceReject(request=false)处理
            throw new RuntimeException(e);
        }
    }*/
    @RabbitListener(queues="demo-queue")
    public void consume05(UserMsg userMsg,Message message,Channel channel){
        log.info("消费者05接收到消息:{}",userMsg);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //如果手动确认失败,底层会按照basiceReject(request=false)处理
            throw new RuntimeException(e);
        }
    }

}
